package queue;

/***
 * 循环队列实现
 * @param <E>
 */
public class RoundRobinQueue<E> implements Queue<E> {

    private transient Object[] array;
    /*** 队列默认最大容量****/
    private static final int DEFAULT_CAPACITY = 1 << 4;
    /*** 头***/
    private int front = 0;
    /*** 尾****/
    private int rear = 0;
    /*** 队列长度****/
    private int size = 0;

    public RoundRobinQueue(int capacity) {
        array = new Object[capacity];
    }

    public RoundRobinQueue() {
        this(DEFAULT_CAPACITY);
    }

    @Override
    public void clear() {
        while (size != 0) {
            remove();
        }
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public E getHead() {
        return (E) array[front];
    }

    @Override
    public void add(E e) {
        if (size < array.length) {
            if (rear < array.length) {
                array[rear] = e;
                rear++;
            } else {
                rear = 0;
            }
            size++;
        } else {
            System.out.println("队列已满");
        }
    }

    @Override
    public void remove() {
        if (front != rear) {

            if (front < array.length) {
                array[front] = null;
                front++;
            } else {
                front = 0;
            }
            size--;
        }
    }

    @Override
    public int size() {
        return size;
    }
}
